package com.ziq.base.view.webview

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.ViewGroup
import android.webkit.*
import com.blankj.utilcode.util.GsonUtils
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.github.lzyzsd.jsbridge.BridgeWebViewClient
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.ziq.base.utils.LogUtil


class BaseWebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : BridgeWebView(context, attrs) {

    var resizeForContent = false

    var jsHandler : JsHandler? = null

    init {
        init()
    }

    @SuppressLint("JavascriptInterface")
    fun init(){
        setWebContentsDebuggingEnabled(true);
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY)

        val settings = settings
        settings.useWideViewPort = false
        settings.mediaPlaybackRequiresUserGesture = false
        settings.builtInZoomControls = true
        settings.displayZoomControls = false;
        settings.javaScriptEnabled = true // 设置是否支持JavaScript
        settings.cacheMode = WebSettings.LOAD_NO_CACHE // 设置缓冲模式

        settings.domStorageEnabled = true

        addJavascriptInterface(this, "zandroid")

        webViewClient = object : BridgeWebViewClient(this) {
            override fun onPageFinished(view: WebView?, url: String?) {
                onPageFinishedCallBack(view, url)
                super.onPageFinished(view, url)
            }
        }

        setDefaultHandler{ data, function ->
            try {
                LogUtil.i("WebView","js call: $data")
                val actionInfo = GsonUtils.fromJson(data, ActionInfo::class.java)
                if(jsHandler == null){
                    function.onCallBack(GsonUtils.toJson(ActionResult()))
                } else {
                    jsHandler?.receiveFromJs(actionInfo, function)
                }
            } catch (e : Exception) {
                LogUtil.i("WebView","js call err: $e")
            }
        }
    }

    fun sendToJs(actionInfo : ActionInfo, callBack: (ActionResult)->Unit) {
        send(GsonUtils.toJson(actionInfo)) {
            val actionResult = GsonUtils.fromJson(it, ActionResult::class.java)
            callBack.invoke(actionResult)
        }
    }

    interface JsHandler {
        fun receiveFromJs(actionInfo : ActionInfo, callback : CallBackFunction)
    }

    class ActionInfo {
        var method : String? = ""
        var parameter : Map<String, Any>? = null
    }

    class ActionResult {
        var code : Int = 0
        var parameter : Map<String, Any>? = null
    }

    fun onPageFinishedCallBack(view: WebView?, url: String?){
        requestContentSize()
    }

    override fun destroy() {
        super.destroy()
        removeCallbacks(resizeRunnable)
    }


    @JavascriptInterface
    fun onContentSizeChange(clientWidth : Int, scrollHeight : Int){
        mClientWidth = clientWidth
        mScrollHeight = scrollHeight
        post(resizeRunnable)
    }

    private fun requestContentSize(){
        if(resizeForContent){
            loadUrl("javascript:zandroid.onContentSizeChange(document.documentElement.clientWidth, document.documentElement.scrollHeight)");
        }
    }

    private var mClientWidth = 0
    private var mScrollHeight = 0
    private var resizeRunnable = Runnable {
        if(mScrollHeight == 0){
            requestContentSize()
        } else {
            (this.layoutParams as? ViewGroup.LayoutParams)?.let {
                val rate: Float = width.toFloat() / mClientWidth.toFloat()
                it.height = (mScrollHeight * rate).toInt()
                this.layoutParams = it
            }
        }
    }

    override fun loadUrl(url: String) {
        try {
            LogUtil.i("WebView","loadUrl:$url")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (url.startsWith("javascript")) {
                    super.evaluateJavascript(url, null)
                } else {
                    super.loadUrl(url)
                }
            } else {
                super.loadUrl(url)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }





}